package com.lzx.adx.report.support.strategy.v3.media;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.CallTypeMappingDTO;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.support.strategy.v2.media.AbstractCallback;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
@MediaType(MediaChannelConstant.BAIDU)
public class BaiduChannel extends AbstractChannel {
    @Override
    public ResponseEntity callback(ReportDTO reportDTO, OcpxAccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        Map<String, CallTypeMappingDTO> callTypeMap = getCallTypeMap(accountDTO);
        CallTypeMappingDTO callTypeMappingDTO = callTypeMap.get(callType);
        String eventType=callTypeMappingDTO.getMediaReturnType();

        String callback = reportDTO.getCallback();
        String decode = URLUtil.decode(callback);
        //解码 并替换数据
        String replace = decode.replace("{{ATYPE}}", eventType).replace("{{AVALUE}}", "0");
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("a_time", Long.valueOf(ts) / 1000);
        if(StringUtils.isNotBlank(reportDTO.getImeiSum()) && !Objects.equals(reportDTO.getImeiSum(), "__")){
            paramsReq.put("join_type", "IMEI");
        }else{
            paramsReq.put("join_type", "OAID");
        }

        String finalUrl = replace + "&" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        log.info("账号id{},请求id{} 给百度上报回传完整的地址：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), finalUrl);
        HttpRequest body = HttpUtil.createGet(finalUrl);
        String result = body.execute().body();
        log.info("账号id{},请求id{} 给百度上报回传结果为 {}", reportDTO.getDspId(), reportDTO.getBizRequestId(), result);

        accountDTO.setFinalURL(finalUrl);
        accountDTO.setBody(result);
        return ResponseEntity.ok(new Result());
    }
}
